import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:geolocator/geolocator.dart';
import 'package:syria_sports/data/remote/location_helper.dart';
import 'package:syria_sports/presentation/gyms/public_gyms_page/models/public_gym.dart';

import '../../../../core/utils/show_toast.dart';
import '../../../../data/controllers/gyms_controller.dart';

part 'gyms_state.dart';

class GymsCubit extends Cubit<GymsState> {
  GymsCubit() : super(GymsInitial());

  static GymsCubit get(context) => BlocProvider.of(context);
  List<PublicGym> gyms = [];
  Position? myLocation;

  void init() {
    getAllGyms();
  }

  getGymsForMyLocation(){
    gyms.removeWhere((gym){
      if(myLocation == null || gym.latitude == null || gym.longitude ==null) return true;
      return !LocationHelper.isWithinFourKm(myLocation!, gym.latitude!.toDouble(),gym.longitude!.toDouble());
    });
    emit(GymsUpdate());
  }

  Future getAllGyms()async{
    emit(GymsLoading());
    await GymsController.getAllPublicGyms().catchError((e){
      print(e);
      emit(GymsError());
      return null;
    }).then((value){
      if(value != null && value.state) {
        gyms = List<PublicGym>.generate(value.data.length, (index) => PublicGym.fromJson(value.data[index]));
        emit(GymsDone());
      }else if(value != null){
        showMessage(value.message);
        emit(GymsError());
      }else{
        if (kDebugMode) {
          print('value is null');
        }
      }
    });
  }
}
